package com.geepi.soundcloud.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import org.apache.commons.lang3.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.geepi.soundcloud.common.MakeOrderNum;
import com.geepi.soundcloud.model.AudioBean;
import com.geepi.soundcloud.model.BaseResponse;
import com.geepi.soundcloud.model.BaseResutlResponse;
import com.geepi.soundcloud.model.Page;
import com.geepi.soundcloud.model.RecordBean;
import com.geepi.soundcloud.model.RecordListInfo;
import com.geepi.soundcloud.service.IOrderService;
import com.google.gson.Gson;
import com.google.gson.JsonArray;

@Controller
public class OrderController {
    @Autowired
	private IOrderService orderService;
	
    private static Logger logger = LoggerFactory.getLogger(OrderController.class);
    
	@RequestMapping("/gethistoryorder")
	@ResponseBody
	public BaseResutlResponse gethistoryorder(@RequestParam("phoneId") String phoneId) {
		logger.info("gethistoryorder..");
		List<RecordBean> recordBeans = orderService.queryHistoryOrderList(phoneId);
		BaseResutlResponse baseResutlResponse = new BaseResutlResponse();
		BaseResponse baseResponse = new BaseResponse();
		if (recordBeans != null) {
			baseResponse.setRc(0);
			baseResponse.setRd("查询订单 success");
			baseResutlResponse.setResponse(recordBeans);
		} else {
			baseResponse.setRc(1);
			baseResponse.setRd("查询订单 is error");
		}
		baseResutlResponse.setResult(baseResponse);
		return baseResutlResponse;
	}
	
	@RequestMapping("/getpriceinfo")
	@ResponseBody
	public BaseResutlResponse getpriceinfo() {
		logger.info("getpriceinfo..");
		BaseResutlResponse baseResutlResponse = new BaseResutlResponse();
		BaseResponse baseResponse = new BaseResponse();
		baseResponse.setRc(0);
		baseResponse.setRd("success");
		baseResutlResponse.setResult(baseResponse);
		
//		{
//			"result": {"rc":返回码,"rd":"返回码描述"}，“response”:{“2h”：“66”，“4h”：“88”，“description”：“￥66元/2小时 ￥88元/4小时”}
//		}
		return baseResutlResponse;
	}
	
	
	@RequestMapping("/getversioninfo")
	@ResponseBody
	public BaseResutlResponse getversioninfo() {
		logger.info("getversioninfo..");
		BaseResutlResponse baseResutlResponse = new BaseResutlResponse();
		String testStr = "{\"1001\":{\"1\":\"2\"},\"1002\":[\"3\",\"4\"]}";
		ObjectMapper mapper = new ObjectMapper();
		HashMap<String, Object> hashMap = new HashMap<String, Object>();
		try {
			hashMap = (HashMap<String, Object>) mapper.readValue(testStr, Map.class);
			Iterator<?> iterator = hashMap.keySet().iterator();   
			while ( iterator.hasNext() ) {
			    Object key = iterator.next();
			    if (!hashMap.get(key).toString().contains("[")) {
			    	continue;
				}
			    List<Object> array = mapper.readValue(hashMap.get(key).toString(),
			    		new TypeReference<List<Object>>() { });
		
			}
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return baseResutlResponse;
	}
	
 	
	@RequestMapping("/gethistoryorder_page")
	@ResponseBody
	public BaseResutlResponse gethistoryorder_page(@RequestParam("phoneId") String phoneId) {
		logger.info("gethistoryorder_page..");
		List<RecordBean> recordBeans = orderService.queryHistoryOrderList(phoneId);
		BaseResutlResponse baseResutlResponse = new BaseResutlResponse();
		BaseResponse baseResponse = new BaseResponse();
		if (recordBeans != null) {
			baseResponse.setRc(0);
			baseResponse.setRd("查询订单 success");
			Page page = new Page();
			page.setMaxPage(1);
			page.setPageNum(1);
			RecordListInfo recordListInfo = new RecordListInfo();
			recordListInfo.setData(recordBeans);
			recordListInfo.setPage(page);
			baseResutlResponse.setResponse(recordListInfo);
		} else {
			baseResponse.setRc(1);
			baseResponse.setRd("查询订单 is error");
		}
		baseResutlResponse.setResult(baseResponse);
		return baseResutlResponse;
	}
	
	/*
	 * 查询运营人员的订单
	 * */
	@RequestMapping("/getunderorder_page")
	@ResponseBody
	public BaseResutlResponse getunderorder_page(@RequestParam("phoneId") String brokerId) {
		logger.info("getunderorder_page:" + brokerId + "end");
		List<RecordBean> recordBeans = orderService.queryUnderOrderList(brokerId);
		BaseResutlResponse baseResutlResponse = new BaseResutlResponse();
		BaseResponse baseResponse = new BaseResponse();
		if (recordBeans != null) {
			baseResponse.setRc(0);
			baseResponse.setRd("查询订单1 success");
			Page page = new Page();
			page.setMaxPage(1);
			page.setPageNum(1);
			RecordListInfo recordListInfo = new RecordListInfo();
			recordListInfo.setData(recordBeans);
			recordListInfo.setPage(page);
			baseResutlResponse.setResponse(recordListInfo);
		} else {
			baseResponse.setRc(1);
			baseResponse.setRd("查询订单 is error");
		}
		baseResutlResponse.setResult(baseResponse);
		return baseResutlResponse;
	}
	
	@RequestMapping("/publishorder")
	@ResponseBody
	public BaseResutlResponse publishorder(@RequestParam("phoneId") String phoneId,
			@RequestParam("starttime") String starttime,
			@RequestParam("endtime") String endtime,
			@RequestParam("address") String address,
			@RequestParam("coursename") String coursename,
			@RequestParam("orderstatus") int orderstatus) {
		logger.info("publishorder..coursename:" + coursename);
		RecordBean recordBean = new RecordBean();
		recordBean.setAddress(address);
		recordBean.setStarttime(starttime);
		recordBean.setEndtime(endtime);
		recordBean.setAddress(address);
		recordBean.setCoursename(coursename);
		recordBean.setPhoneId(phoneId);
		recordBean.setOrderid(MakeOrderNum.makeOrderNum());
		recordBean.setBrokerId("15581631439");
		
		BaseResutlResponse baseResutlResponse = new BaseResutlResponse();
		boolean result = orderService.publishOrder(recordBean);
		if (result) {
			//query order info
			recordBean = orderService.queryOrderDetail(recordBean.getOrderid());
			BaseResponse baseResponse = new BaseResponse();
			baseResponse.setRc(0);
			baseResponse.setRd("publishorder success");
			baseResutlResponse.setResult(baseResponse);
			baseResutlResponse.setResponse(recordBean);
		} else {
			BaseResponse baseResponse = new BaseResponse();
			baseResponse.setRc(1);
			baseResponse.setRd("publishorder error");
			baseResutlResponse.setResult(baseResponse);
		}

		return baseResutlResponse;
	}
	
	@RequestMapping("/deleteorder")
	@ResponseBody
	public BaseResutlResponse deleteorder(@RequestParam("phoneId") String phoneId,
			@RequestParam("orderid") String orderid) {
		logger.info("deleteorder.." + orderid);
		boolean result = orderService.delOrder(orderid);
		BaseResutlResponse baseResutlResponse = new BaseResutlResponse();
		if (result) {
			BaseResponse baseResponse = new BaseResponse();
			baseResponse.setRc(0);
			baseResponse.setRd("del order success");
			baseResutlResponse.setResult(baseResponse);
		} else {
			BaseResponse baseResponse = new BaseResponse();
			baseResponse.setRc(2);
			baseResponse.setRd("del order error");
			baseResutlResponse.setResult(baseResponse);
		}
		return baseResutlResponse;
	}
	
	@RequestMapping("/setorderstatus")
	@ResponseBody
	public BaseResutlResponse setorderstatus(@RequestParam("phoneId") String phoneId,
			@RequestParam(value="orderids", required=false) String orderids,
			@RequestParam(value="orderid", required=false) String orderid,
			@RequestParam(value="orderstatus", required=false) Integer orderstatus) {
		//如果参数是非必须的，则会赋值为null，因此参数应该是一个object，它才能接受这个null值。
		logger.info("setorderstatus.." + orderids);
		if (StringUtils.isEmpty(orderids)) {
			//单条记录
			boolean result = orderService.updateOrderStatus(orderid, orderstatus);
			BaseResutlResponse baseResutlResponse = new BaseResutlResponse();
			if (result) {
				BaseResponse baseResponse = new BaseResponse();
				baseResponse.setRc(0);
				baseResponse.setRd("update order success");
				baseResutlResponse.setResult(baseResponse);
			} else {
				BaseResponse baseResponse = new BaseResponse();
				baseResponse.setRc(2);
				baseResponse.setRd("update order error");
				baseResutlResponse.setResult(baseResponse);
			}
			return baseResutlResponse;
		}
		ObjectMapper mapper = new ObjectMapper();
		try {
			List<HashMap<String, Object>>  array = mapper.readValue(orderids,
					new TypeReference<List<Object>>() { });
		    for (int i = 0; i < array.size(); i++) {
				HashMap<String, Object> hashMap = array.get(i);
				boolean result = orderService.updateOrderStatus(hashMap.get("orderid").toString(), Integer.parseInt(hashMap.get("orderstatus").toString()));
				BaseResutlResponse baseResutlResponse = new BaseResutlResponse();
				if (result) {
					BaseResponse baseResponse = new BaseResponse();
					baseResponse.setRc(0);
					baseResponse.setRd("update order success");
					baseResutlResponse.setResult(baseResponse);
				} else {
					BaseResponse baseResponse = new BaseResponse();
					baseResponse.setRc(2);
					baseResponse.setRd("update order error");
					baseResutlResponse.setResult(baseResponse);
				}
				return baseResutlResponse;
			}
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	@RequestMapping("/getorderdescribe")
	@ResponseBody
	public BaseResutlResponse getorderdescribe(@RequestParam("phoneId") String phoneId,
			@RequestParam("orderid") String orderId) {
		logger.info("setorderstatus.." + orderId);
		RecordBean recordBean = orderService.queryOrderDetail(orderId);
		BaseResutlResponse baseResutlResponse = new BaseResutlResponse();
		if (recordBean != null) {
			BaseResponse baseResponse = new BaseResponse();
			baseResponse.setRc(0);
			baseResponse.setRd("query order success");
			baseResutlResponse.setResult(baseResponse);
			baseResutlResponse.setResponse(recordBean);
		} else {
			BaseResponse baseResponse = new BaseResponse();
			baseResponse.setRc(2);
			baseResponse.setRd("query order error");
			baseResutlResponse.setResult(baseResponse);
		}
		return baseResutlResponse;
	}
	
	@RequestMapping("/addorderpieceinfo")
	@ResponseBody
	public BaseResutlResponse addorderpieceinfo(@RequestParam("phoneId") String phoneId,
			@RequestParam("orderids") String orderids,
			@RequestParam("ordercount") int ordercount,
			@RequestParam("pieceurl") String pieceurl,
			@RequestParam("starttime") String starttime,
			@RequestParam("endtime") String endtime) {
		logger.info("addorderpieceinfo.." + orderids);
		ObjectMapper mapper = new ObjectMapper();
	    try {
			List<String> array = mapper.readValue(orderids,
					new TypeReference<List<String>>() { });
			//query audio count by orderId
			String orderId = array.get(0);
			int count =  orderService.queryAudioList(orderId).size();
			
			AudioBean audioBean = new AudioBean();
			audioBean.setPieceid(count);
			audioBean.setPiecestarttime(starttime);
			audioBean.setPieceendtime(endtime);
			audioBean.setPieceurl(pieceurl);
			audioBean.setRelatedOrder(orderids);
			boolean result = orderService.addAudioInfo(audioBean);
			BaseResutlResponse baseResutlResponse = new BaseResutlResponse();
			if (result == true) {
				BaseResponse baseResponse = new BaseResponse();
				baseResponse.setRc(0);
				baseResponse.setRd("qaddorderpieceinfo success");
				baseResutlResponse.setResult(baseResponse);
			} else {
				BaseResponse baseResponse = new BaseResponse();
				baseResponse.setRc(2);
				baseResponse.setRd("addorderpieceinfo error");
				baseResutlResponse.setResult(baseResponse);
			}
			return baseResutlResponse;
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    return null;
	}
	
	
}
